#include "../inc/keypress.h"
#include "../inc/init.h"
#include <SDL_image.h>

SDL_Window *gCurSurface = NULL;
SDL_Window *gKeyPressSurfaces[KEY_PRESS_SURFACE_TOTAL];

SDL_Surface* loadSurfaceFromImg(const char* imgPath){
    SDL_Surface *optiSurface = NULL;
    SDL_Surface *surface = IMG_Load(imgPath);
    if(!surface){
        SDL_Log("Could not load image from path %s: %s\n", imgPath, IMG_GetError());
    }else{
        optiSurface = SDL_ConvertSurface(surface, gWinSurface->format, 0);
        if(!optiSurface){
            SDL_Log("Could not convert surface: %s\n", SDL_GetError());
        }
        SDL_FreeSurface(surface);
    }
    return optiSurface;
}

bool loadMedia(void){
    bool success = true;

    gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT] = loadSurfaceFromImg("./img/default.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT]){
        SDL_Log("Failed to load default image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_UP] = loadSurfaceFromImg("./img/up.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_UP]){
        SDL_Log("Failed to load up image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN] = loadSurfaceFromImg("./img/down.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN]){
        SDL_Log("Failed to load down image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT] = loadSurfaceFromImg("./img/left.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT]){
        SDL_Log("Failed to load left image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT] = loadSurfaceFromImg("./img/right.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT]){
        SDL_Log("Failed to load right image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_SPACE] = loadSurfaceFromImg("./img/space.bmp");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_SPACE]){
        SDL_Log("Failed to load space image!\n");
        success = false;
    }

    gKeyPressSurfaces[KEY_PRESS_SURFACE_ENTER] = loadSurfaceFromImg("./img/enter.png");
    if(!gKeyPressSurfaces[KEY_PRESS_SURFACE_ENTER]){
        SDL_Log("Failed to load enter image!\n");
        success = false;
    }

    return success;
}

void freeMedia(void){
    for(int i = 0; i < KEY_PRESS_SURFACE_TOTAL; i++){
        SDL_FreeSurface(gKeyPressSurfaces[i]);
        gKeyPressSurfaces[i] = NULL;
    }
    SDL_DestroyWindow(gWin);
    gWin = NULL;
    SDL_Quit();
}




